<?php

namespace app\store\service;

use app\store\model\Task;
use think\facade\Db;

class TaskService
{
    public static function getTaskList($param)
    {
        $store_id = session('store_id');

        $query = Db::name('activity_task')
            ->alias('a')
            ->field('a.id,a.task_type,b.activity_title,c.combo_name,a.join_num,a.expire_type,a.expire_time,a.start_time,a.end_time,
            a.status,a.create_time,a.update_time,a.give_integral')
            ->leftjoin('group_activity b','a.group_activity_id=b.id')
            ->leftjoin('combo c','a.user_combo_id=c.id')
            ->withAttr('start_time',function ($value){
                if (empty($value)){
                    return  $value;
                }
                return date('Y-m-d H:i:s',$value);
            })->withAttr('end_time',function ($value){
                if (empty($value)){
                    return  $value;
                }
                return date('Y-m-d H:i:s',$value);
            })->where(['a.store_id' => $store_id]);


        if (!empty($param['task_type'])){
            $query->where('a.task_type',$param['task_type']);
        }

        if (!empty($param['start_time']) && !empty($param['end_time'])){
            $query->whereBetweenTime('a.create_time',$param['start_time'],$param['end_time']);
        }



        $taskList = $query->order('id','desc')->paginate(10);

        return $taskList;
    }

    public static function findTask($id)
    {
        $task = Db::name('activity_task')->withoutField('create_time,update_time,delete_time')
                     ->where('id',$id)
                     ->find();



        $coupons = [];

        if (!empty($task['give_coupon'])){
            $give_coupon = json_decode($task['give_coupon'],true);
            $ids = array_column($give_coupon,'coupon_id');
            $couponList = Db::name('coupon')
                ->field('id,icon,coupon_name')
                ->whereIn('id',$ids)
                ->select();


            foreach ($couponList as $k => $v){
                $coupons[$k]['coupon_id'] = $v['id'];
                $coupons[$k]['coupon_icon'] = $v['icon'];
                $coupons[$k]['coupon_name'] = $v['coupon_name'];
                $coupons[$k]['give_num'] = $give_coupon[$k]['give_num'];
            }
            $task['coupons_info'] = $coupons;
        }



        return $task;
    }
}